package com.asman.worker.multishow

import android.os.Environment
import com.asman.worker.utils.MD5Utils
import java.io.File

/**
 * @author ybk
 * @date :2020/2/10 1:08 PM
 * @desc:
 */
object FileUtils {

    /**
     * 生成本地文件名
     * @param url 远程文件路径 https://asman-app.oss-cn-hangzhou.aliyuncs.com/video/app_test1.mp4
     * return 本地文件名  66e6074a8d19894e_app_test1.mp4
     */
    fun generatorLocalFileName(url: String?): String {
        val urlMD5 = MD5Utils.getMD5Str(url).substring(0, 16)//MD5 取16位
        val fileName = url?.substringAfterLast("/")
        return urlMD5 + "_" + fileName
    }

    fun isFileDownloaded(url: String?, dirName: String? = "牛大匠"): Boolean {
        return if (url != null && (url.startsWith("https://") || url.startsWith("http://"))) {
            val localFileName = generatorLocalFileName(url)
            val file = File(Environment.getExternalStorageDirectory(), "/${dirName}/$localFileName")
            file.exists()
        }else{
            true
        }
    }

    /**
     * 获取播放地址，优先播放本地
     */
    fun getOriginFilePath(url: String?, dirName: String? = "牛大匠"): String? {
        //本地文件名
        val localFileName = generatorLocalFileName(url)
        val file = File(Environment.getExternalStorageDirectory(), "/${dirName}/$localFileName")
        return if (file.exists()) {
            file.absolutePath
        } else {
            url
        }
    }

}